import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { createJSONStorage, persist } from 'zustand/middleware';

interface State {
  name: string;
  age: number;
  changeName?: () => void;
  getAge?: () => void;
}
const useUserStore = create<State>()(
  immer(
    // immer 中间件的主要作用是简化不可变状态更新
    persist(
      (set, get) => ({
        name: 'zs',
        age: 18,
        changeName: () => set((state) => ({ name: `${state.name}-111` })),
        getAge: () => get().age,
      }),
      {
        name: 'userName',
        storage: createJSONStorage(() => localStorage),
        partialize: (state) => ({
          name: state.name,
        }),
      },
    ),
  ),
);
export default useUserStore;
